/*
 * Copyright 2025 arisgo@163.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.arisgo.cloud.web.configurer.filter;

import com.google.common.collect.Maps;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;

import java.util.Map;

/**
 * 装饰者模式
 * @author Arisgo
 * @since 2024/6/14
 */
public class RequestParameterWrapper extends HttpServletRequestWrapper {
    private final Map<String, String[]> params = Maps.newHashMap();
    public RequestParameterWrapper(HttpServletRequest request) {
        super(request);
        this.params.putAll(request.getParameterMap());
    }

    public RequestParameterWrapper(HttpServletRequest request, Map<String, Object> params) {
        this(request);
        //这里将扩展参数写入参数表
        addParameters(params);
    }

    public static RequestParameterWrapper creator(HttpServletRequest request, Map<String, Object> params) {
        return new RequestParameterWrapper(request, params);
    }

    public static RequestParameterWrapper creator(HttpServletRequest request, String key, Object value) {
        Map<String, Object> params = Maps.newHashMap();
        params.put(key, value);
        return new RequestParameterWrapper(request, params);
    }

    private void addParameters(Map<String, Object> params) {
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            addParameter(entry.getKey(), entry.getValue());
        }
    }

    private void addParameter(String name, Object value) {
        if (value != null) {
            if (value instanceof String[] val) {
                params.put(name, val);
            } else if (value instanceof String val) {
                params.put(name, new String[]{val});
            } else {
                params.put(name, new String[]{String.valueOf(value)});
            }
        }
    }

    @Override
    public String getParameter(String name) {
        String[] values = params.get(name);
        if (values == null || values.length == 0) {
            return null;
        }
        return values[0];
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] values = params.get(name);
        if (values == null || values.length == 0) {
            return null;
        }
        return values;
    }

}
